package com.example.mybank.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybank.entity.Debit;
import com.example.mybank.entity.Users;
import com.example.mybank.mapper.DebitMapper;
import com.example.mybank.springSecurity.UserHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/debit")
public class DebitController {

    @Autowired
    DebitMapper debitMapper;

    // 管理员：获取所有贷款记录
    @GetMapping("/all")
    public List<Debit> getAll(){
        return debitMapper.selectList(null);
    }

    // 用户：查看自己的贷款记录
    @GetMapping("/user/{userID}")
    public List<Debit> getByUser(@PathVariable("userID") int userID){
        QueryWrapper<Debit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user",userID);
        return debitMapper.selectList(null);
    }

    // 用户：查看账户的贷款记录
    @GetMapping("/account/{accountID}")
    public List<Debit> getByAccount(@PathVariable("accountID") int accountID){
        QueryWrapper<Debit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("accountID",accountID);
        return debitMapper.selectList(null);
    }

    // 贷款
    @GetMapping("/add/{accountID}/{money}")
    public Boolean add(@PathVariable("accountID") int accountID,
                           @PathVariable("money") int money){
        UserHandler principal = (UserHandler) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Users users = principal.getUsers();

        Debit debit = new Debit(0L, money, new Date(), new Date(System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000), Boolean.FALSE, Boolean.FALSE,(long) accountID, null, users.getId());
        debitMapper.insert(debit);

        return Boolean.TRUE;
    }


}
